/*
 * ListaMedicosPanel.java
 *
 * Created on 02/11/2010, 19:05:11
 */
package clinicapoo.view.medic;

import clinicapoo.factory.Services;
import clinicapoo.model.Especialidade;
import clinicapoo.model.Medico;
import clinicapoo.view.dialog.Dialogs;
import clinicapoo.view.utils.CellRenderer;
import clinicapoo.view.utils.ComboBox;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import static clinicapoo.message.MessageResources.msg;

/**
 *
 * @author Fabio Montezuma
 */
public class ListaMedicosPanel extends javax.swing.JInternalFrame implements TableModelListener
{
	private List<Medico> listaMedicos;
	private List<Especialidade> listaEspecialidades;

	/** Creates new form ListaMedicosPanel */
	public ListaMedicosPanel()
	{
		initComponents();
		mostrarListaMedicos();
		tblMedicos.getModel().addTableModelListener(this);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblMedicos = new javax.swing.JTable();
        btnExcluir = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("resources/messages"); // NOI18N
        setTitle(bundle.getString("view.medic.lista.title")); // NOI18N

        tblMedicos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tblMedicos.setAutoscrolls(false);
        tblMedicos.setMinimumSize(new java.awt.Dimension(500, 0));
        tblMedicos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblMedicosKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblMedicos);

        btnExcluir.setText(bundle.getString("view.medic.lista.excluir")); // NOI18N
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(520, Short.MAX_VALUE)
                .addComponent(btnExcluir)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnExcluir)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblMedicosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblMedicosKeyPressed
		if (evt.getKeyCode() == KeyEvent.VK_DELETE)
		{
			excluirMedicoSelecionado();
		}
    }//GEN-LAST:event_tblMedicosKeyPressed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnExcluirActionPerformed
    {//GEN-HEADEREND:event_btnExcluirActionPerformed
		excluirMedicoSelecionado();
    }//GEN-LAST:event_btnExcluirActionPerformed

	public void mostrarListaMedicos()
	{
		try
		{
			listaMedicos = Services.medico.listar();
			listaEspecialidades = Services.especialidade.listar();
			Vector<String> nomesEspecialidades = new Vector<String>();

			for (Especialidade esp : listaEspecialidades)
			{
				nomesEspecialidades.add(esp.getNome());
			}

			Vector<String> tableHeaders = new Vector<String>();
			Vector tableData = new Vector();

			tableHeaders.add(msg("view.medic.lista.campos.especialidade"));
			tableHeaders.add(msg("view.medic.lista.campos.cpf"));
			tableHeaders.add(msg("view.medic.lista.campos.crm"));
			tableHeaders.add(msg("view.medic.lista.campos.nome"));
			tableHeaders.add(msg("view.medic.lista.campos.telefone"));
			tableHeaders.add(msg("view.medic.lista.campos.celular"));
			tableHeaders.add(msg("view.medic.lista.campos.endereco"));

			for (Medico m : listaMedicos)
			{
				Vector<Object> oneRow = new Vector<Object>();
				oneRow.add(m.getEspecialidade());
				oneRow.add(m.getCpf());
				oneRow.add(m.getCrm());
				oneRow.add(m.getNome());
				oneRow.add(m.getTelefone());
				oneRow.add(m.getCelular());
				oneRow.add(m.getEndereco());
				tableData.add(oneRow);
			}
			tblMedicos.setModel(new DefaultTableModel(tableData, tableHeaders));

			int columnIndex = tblMedicos.getColumnModel().getColumnIndex(msg("view.medic.lista.campos.especialidade"));
			TableColumn column = tblMedicos.getColumnModel().getColumn(columnIndex);
			column.setCellRenderer(new CellRenderer());
			column.setCellEditor(new DefaultCellEditor(new ComboBox(listaEspecialidades)));
			
		}
		catch (Exception e)
		{
			Dialogs.showError(this, e);
		}
	}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExcluir;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblMedicos;
    // End of variables declaration//GEN-END:variables

	private void excluirMedicoSelecionado()
	{
		try
		{
			int rowIndex = tblMedicos.getSelectedRow();

			if (rowIndex >= 0)
			{
				if (Dialogs.showQuestion(this, msg("view.medic.excluir.confirm")) == Dialogs.YES)
				{
					Medico m = listaMedicos.get(rowIndex);
					Services.medico.excluir(m);
					mostrarListaMedicos();
					Dialogs.showInfo(this, msg("view.medic.excluir.sucesso"));
				}
			}
		}
		catch (Exception e)
		{
			Dialogs.showError(this, e);
		}
	}

	@Override
	public void tableChanged(TableModelEvent event)
	{
		Object dataBackup = null;
		int row = event.getFirstRow();
		int column = event.getColumn();
		String columnName = tblMedicos.getModel().getColumnName(column);
		Object data = tblMedicos.getModel().getValueAt(row, column);
		Medico m = listaMedicos.get(row);

		if (columnName.equals(msg("view.medic.lista.campos.especialidade")))
		{
			dataBackup = m.getEspecialidade();
			m.setEspecialidade((Especialidade) data);
		}
		if (columnName.equals(msg("view.medic.lista.campos.cpf")))
		{
			dataBackup = m.getCpf();
			m.setCpf((String) data);
		}
		else if (columnName.equals(msg("view.medic.lista.campos.crm")))
		{
			dataBackup = m.getCrm();
			m.setCrm((String) data);
		}
		else if (columnName.equals(msg("view.medic.lista.campos.nome")))
		{
			dataBackup = m.getNome();
			m.setNome((String) data);
		}
		else if (columnName.equals(msg("view.medic.lista.campos.telefone")))
		{
			dataBackup = m.getTelefone();
			m.setTelefone((String) data);
		}
		else if (columnName.equals(msg("view.medic.lista.campos.celular")))
		{
			dataBackup = m.getCelular();
			m.setCelular((String) data);
		}
		else if (columnName.equals(msg("view.medic.lista.campos.endereco")))
		{
			dataBackup = m.getEndereco();
			m.setEndereco((String) data);
		}

		try
		{
			Services.medico.editar(m);
		}
		catch (Exception e)
		{
			Dialogs.showError(this, e);
			tblMedicos.getModel().setValueAt(dataBackup, row, column);
		}
	}
}
